#!/bin/ksh

if [[ $# -ne 1 ]] ; then echo "Usage: $0 v2.mean" ; exit ; fi

infile=input_files/$1
if [[ ! -s $infile ]] ; then echo "$infile not found" ; exit ; fi

fortran_compile=$FC
if [[ $FC = '' ]]
then echo "set an environment variable FC to the fortran_compile_command like f90"
     echo "or do all compilation first and comment the compilation lines"
     exit
fi

echo "Bringing Antarctic tables closer to ${infile} format"
./antarc_to_v2.sh

echo "adding extra Antarctica station data to ${infile}"
${fortran_compile} antarc_comb.f -o antarc_comb.exe
antarc_comb.exe v2_antarct.dat ${infile}
echo "created v2.meanx from v2_antarct.dat and ${infile}"
rm -f v2_antarct.dat antarc_comb.exe

echo "removing pre-1880 data:"
${fortran_compile} dump_old.f -o dump_old.exe
dump_old.exe v2.meanx v2.meany 1880 ; echo "created v2.meany from v2.meanx"
rm -f v2.meanx

echo "replacing USHCN1 data in $1 by USHCN_noFIL data (Tobs+maxmin adj+SHAPadj+noFIL)"

echo "  reformat USHCN to v2.mean format"
${fortran_compile} USHCN2v2.f -o USHCN2v2.exe ; ./get_USHCN

echo "finding offset caused by adjustments"
grep ^425 v2.meany > ghcn_us
dump_old.exe ghcn_us ghcn_us_end 1980
grep -v -e -9999-9999-9999-9999-9999-9999-9999-9999-9999-9999-9999-9999  USHCN.v2.mean_noFIL > xxx

dump_old.exe xxx yyy 1880  ; rm -f xxx
sort -n yyy > USHCN.v2.mean_noFIL ; rm -f yyy
${fortran_compile} dif.ushcn.ghcn.2005.f -o dif.ushcn.ghcn.2005.exe ; dif.ushcn.ghcn.2005.exe
echo "created ushcn-ghcn_offset_noFIL "
${fortran_compile} cmb2.ushcn.v2.f -o cmb2.ushcn.v2.exe ; cmb2.ushcn.v2.exe > ushcn.log
echo "created  v2.meanz"

echo "replacing Hohenspeissenberg data in $1 by more complete data (priv.comm.)"
echo "disregard pre-1880 data:"
tail +100 input_files/t_hohenpeissenberg_200306.txt_as_received_July17_2003 > t_hohenpeissenberg
${fortran_compile} hohp_to_v2.f -o hohp_to_v2.exe  ; hohp_to_v2.exe
${fortran_compile} cmb.hohenp.v2.f -o cmb.hohenp.v2.exe
cmb.hohenp.v2.exe

# cleanup
mkdir to_next_step 2> /dev/null
mkdir work_files   2> /dev/null
mv    v2.mean to_next_step/v2.mean_comb
mv *exe v2.mean* ghcn* ushcn* hcn* USHCN.v2.mean_noFIL ID_US_G *hohenpeiss* work_files/.
